package com.wondertek.poms.core.service.impl;

import cn.hutool.core.convert.Convert;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.config.MsgConfig;
import com.wondertek.poms.core.service.IContentBlackService;
import com.wondertek.poms.core.service.IContentService;
import com.wondertek.poms.core.service.IContentWhiteService;
import com.wondertek.poms.core.service.IProductInfoPackageService;
import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.ContentWhite;
import com.wondertek.poms.dao.po.PlanMovePrdInfo;
import com.wondertek.poms.dao.po.ProductInfoPackage;
import com.wondertek.poms.dao.vo.ContentBlackVo;
import com.wondertek.poms.dao.vo.ContentWhiteVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p><b>ContentWhiteServiceImpl Description:</b> 白名单表service层实现 </p>
 * @author 窦再兴
 * <p><b>DATE</b> 2020-12-03 10:19:26</p>
 */
@Service
@Scope("prototype")
public class ContentWhiteServiceImpl extends ServiceImpl<ContentWhite, Long> implements IContentWhiteService {

	@Autowired
	private IProductInfoPackageService productInfoPackageService;
	@Autowired
	private IContentBlackService contentBlackService;
	@Autowired
	private IContentService contentService;
	@PersistenceContext
    public EntityManager entityManager;
	@Autowired
	private MsgConfig msgConfig;

	@Override
	@Transactional
	public ContentWhite deleteLogic(Long id) {
		ContentWhite cp = jpaRepository.getOne(id);
		ContentWhite.putTimeAndUser(cp);
		cp.setDeleted(Constants.DELETE_1);
		jpaRepository.save(cp);
		return cp;
	}

	@Override
	@Transactional
	public ContentWhite merge(ContentWhite model) {
		ContentWhite.putTimeAndUser(model);
		ContentWhite dbo = jpaRepository.getOne(model.getId());
		CopyUtils.copyProperties(model, dbo);
		return jpaRepository.save(dbo);
	}

	@Override
	public Page<ContentWhiteVo> findPage(ContentWhiteVo contentWhiteVo, int page, int rows, String sidx, String sord) {
		String condition = sqlStringWhere(true,contentWhiteVo);
		Object o = entityManager
				.createNativeQuery(condition).getSingleResult();
		int count = Convert.toInt(o);
		Pageable pageable = PageRequest.of(page - 1, rows);
		if(count>0){
			condition=sqlStringWhere(false,contentWhiteVo);
			Query query=entityManager.createNativeQuery(condition);
			query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
			query.setMaxResults(pageable.getPageSize());
			List<Object[]> list=query.getResultList();
			List<ContentWhiteVo> contentBlacklist=toContentWhitelist(list);;
			PageImpl<ContentWhiteVo> result=new PageImpl<ContentWhiteVo>(contentBlacklist,pageable,count);
			entityManager.close();
			return result;
		}
		entityManager.close();
		return  Page.empty(pageable);
	}

	@Override
	public ResultBean saveOne(ContentWhiteVo contentWhiteVo) {
		ContentBlackVo contentBlackVo = new ContentBlackVo();
		BeanUtils.copyProperties(contentWhiteVo, contentBlackVo);
		ContentWhite contentWhite = new ContentWhite();
		BeanUtils.copyProperties(contentWhiteVo, contentWhite);
		if(StringUtils.isBlank(contentWhiteVo.getContentName())){
			Content content0=new Content();
			content0.setContentId(contentWhiteVo.getContentId());
			List<Content> list=contentService.findAll(content0);
			if(list!=null && list.size()>0){
				Content content=list.get(0);
				if(content!=null && StringUtils.isNotBlank(content.getName())){
					contentWhite.setContentName(content.getName());
				}
			}else{
				return ResultBean.error("该内容id在本平台不存在");
			}
		}
		Map<String,String> judgeMap=contentBlackService.isRepeat(contentBlackVo,1);
		//该内容对应的商品包的黑名单已存在
		if(StringUtils.isNotBlank(judgeMap.get("1"))) {
			return ResultBean.error(msgConfig.getBlacklistAlreadyExisted());
			//该内容对应的商品包的白名单已存在
		}else if(StringUtils.isNotBlank(judgeMap.get("22"))){
			return ResultBean.error("该商品包对应的二级产品"+judgeMap.get("21")+"下有别的商品包已配置白名单商品包:"+judgeMap.get("22").substring(1));
		}else if(StringUtils.isNotBlank(judgeMap.get("2"))){
			return ResultBean.error(msgConfig.getWhitelistAlreadyExisted());
		}
		if(contentWhite.getPackageId()!=null && StringUtils.isBlank(contentWhite.getPackageName())){
			ProductInfoPackage productInfoPackage =productInfoPackageService.get(contentWhite.getPackageId());
			if(productInfoPackage!=null){
				contentWhite.setPackageName(productInfoPackage.getProductInfoPackageName());
			}
		}
		ContentWhite.putTimeAndUser(contentWhite);
		save(contentWhite);
		return ResultBean.ok();
	}

	List<ContentWhiteVo> toContentWhitelist(List<Object[]> list){
		List<ContentWhiteVo> contentBlacklist=new ArrayList<>();
		for (Object[] obj:list){
			ContentWhiteVo contentBlack=new ContentWhiteVo();
			contentBlack.setContentId (StringUtil.null2Str(obj[0]));
			contentBlack.setPackageId(StringUtil.nullToLong(obj[1]));
			contentBlack.setPrdInfoId (StringUtil.nullToLong(obj[2]));
			contentBlack.setRemarks(StringUtil.null2Str(obj[3]));
			contentBlack.setCreatedBy (StringUtil.null2Str(obj[4]));
			contentBlack.setCreatedTime(StringUtil.null2Str(obj[5]));
			contentBlack.setUpdatedTime(StringUtil.null2Str(obj[6]));
			contentBlack.setContentName (StringUtil.null2Str(obj[7]));
			contentBlack.setPackageName (StringUtil.null2Str(obj[8]));
			contentBlack.setPrdInfoName (StringUtil.null2Str(obj[9]));
			contentBlack.setId (StringUtil.nullToLong(obj[10]));
			contentBlacklist.add(contentBlack);
		}
		return contentBlacklist;
	}


	public String sqlStringWhere(boolean getCount, ContentWhiteVo contentWhiteVo) {
		StringBuilder condition = new StringBuilder();
		if (getCount) {
			condition.append("select count(0) ");
		} else {
			condition.append("select CONTENT_ID,PACKAGE_ID,PRD_INFO_ID,REMARKS,CREATED_BY,to_char(CREATED_TIME,'YYYY-MM-DD HH24:MI:SS'),to_char(UPDATED_TIME,'YYYY-MM-DD HH24:MI:SS') ,CONTENT_NAME,PACKAGE_NAME,PRD_INFO_NAME,ID ");
		}
		condition.append(" from CONTENT_WHITE where deleted =0 ");
		if (contentWhiteVo != null) {
			if (StringUtils.isNotBlank(contentWhiteVo.getContentId())) {
				condition.append(" and CONTENT_ID = " + contentWhiteVo.getContentId());
			}
			if (contentWhiteVo.getPackageId() != null) {
				condition.append(" and PACKAGE_ID = " + contentWhiteVo.getPackageId());
			}
			if (contentWhiteVo.getPrdInfoId() != null) {
				condition.append(" and PRD_INFO_ID = " + contentWhiteVo.getPrdInfoId());
			}
			if (StringUtils.isNotBlank(contentWhiteVo.getCreatedStartTime())) {
				condition.append(" and CREATED_TIME > TO_DATE('" + contentWhiteVo.getCreatedStartTime() + "', 'yyyy-MM-dd HH24:MI:SS')");
			}
			if (StringUtils.isNotBlank(contentWhiteVo.getCreatedEndTime())) {
				condition.append(" and CREATED_TIME <= TO_DATE('" + contentWhiteVo.getCreatedEndTime() + "', 'yyyy-MM-dd HH24:MI:SS')+1");
			}
		}
		condition.append(" order by CREATED_TIME desc ");
		return condition.toString();
	}


}